/*
  This file is part of Open-Doors.

  Open-Doors is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
  
  Open-Doors is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with Open-Doors.  If not, see <http://www.gnu.org/licenses/>.

  Authors: Rune Thorbek & Araz B. Makoo
*/ 

var is_admin = false;

Ext.define('OpenDoors.controller.Controller', {
    extend: 'Ext.app.Controller',

    stores: ['Menuitems', 'Indsamlere', 'Grupper', 'Ruter', 'Kampagner', 'GruppensIndsamlere'],
    
    init: function() {
        this.control({
            'menulist': {
                selectionchange: this.onMenuItemSelect,
	    },
	    'grid': {
		itemdblclick: this.onGridDblClicked,
	    },
	    'button': {
		click: this.onButtonClick
	    }
        });
    },
    
    onLaunch: function() {
        var menuitemsStore = this.getMenuitemsStore();        
    
	Ext.Ajax.request({
	    url: 'db_functions.php',
	    method: 'post',
	    params: {
		function  : 'get_login_username'
	    },
	    success: function(response, object) {
		var res = Ext.decode(response.responseText);
		
		if (res.success == true){
		    if (res.msg == "admin") {
			is_admin = true;
			var r = Ext.ModelManager.create({
			    id: 6, 
			    name: 'Administration'
			}, 'OpenDoors.model.Menuitems');
			menuitemsStore.insert(5, r);

			//Ext.getCmp('add_rute_button').show();
			Ext.getCmp('add_venue_button').show();
			Ext.getCmp('delete_rute_menuitem').show();
			Ext.getCmp('edit_venue_menuitem').show();
			Ext.getCmp('delete_venue_menuitem').show();
			Ext.getCmp('delete_kampagne_menuitem').show();
		    }
		}
		
		var menuitemsList = Ext.getCmp("menulist_grid");
		menuitemsList.getSelectionModel().select(0);
		
	    }
	});

	adjust_size();
    },

    
    onMenuItemSelect: function(selModel, selection) {
	var selected_value = selection[0].get('name');
	if (selected_value == "Administration") {
	    Ext.getCmp("venues_view_panel").hide();
	    Ext.getCmp("administration_view_panel").show();
	    Ext.getCmp("indsamlere_view_panel").hide();
	    Ext.getCmp("grupper_view_panel").hide();
	    Ext.getCmp("ruter_view_panel").hide();
	    Ext.getCmp("kampagner_view_panel").hide();
	} else if (selected_value == "Indsamlere"){
	    search("indsamlere");
	    Ext.getCmp("venues_view_panel").hide();
            Ext.getCmp("indsamlere_view_panel").show();
	    Ext.getCmp("administration_view_panel").hide();
	    Ext.getCmp("grupper_view_panel").hide();
	    Ext.getCmp("ruter_view_panel").hide();
	    Ext.getCmp("kampagner_view_panel").hide();
	} else if (selected_value == "Indsamlingsgrupper"){
	    search("grupper");
	    Ext.getCmp("venues_view_panel").hide();
	    Ext.getCmp("indsamlere_view_panel").hide();
	    Ext.getCmp("administration_view_panel").hide();
	    Ext.getCmp("grupper_view_panel").show();
	    Ext.getCmp("ruter_view_panel").hide();
	    Ext.getCmp("kampagner_view_panel").hide();
	} else if (selected_value == "Ruter") {
	    search("ruter");
	    Ext.getCmp("venues_view_panel").hide();
	    Ext.getCmp("ruter_view_panel").show();
	    Ext.getCmp("indsamlere_view_panel").hide();
	    Ext.getCmp("administration_view_panel").hide();
	    Ext.getCmp("grupper_view_panel").hide();
	    Ext.getCmp("kampagner_view_panel").hide();
	} else if (selected_value == "Mødesteder") {
	    search("venues");
	    
	    Ext.Ajax.request({
		url: 'db_functions.php',
		method: 'post',
		params: {
		    function: 'get_total_amount'
		},
		success: function(response, object) {
		    var res = Ext.decode(response.responseText);
		    
		    if (res.success == true){
			total = res.msg.replace(".", ",")
			Ext.getCmp("total_indsamlet_label").setText('Total indsamlet beløb: ' + total);
		    }
		}
	    });
	    
	    Ext.getCmp("venues_view_panel").show();
	    Ext.getCmp("ruter_view_panel").hide();
	    Ext.getCmp("indsamlere_view_panel").hide();
	    Ext.getCmp("administration_view_panel").hide();
	    Ext.getCmp("grupper_view_panel").hide();
	    Ext.getCmp("kampagner_view_panel").hide();
	} else if (selected_value == "Kampagner") {
	    search("kampagner");
	    Ext.getCmp("venues_view_panel").hide();
	    Ext.getCmp("ruter_view_panel").hide();
	    Ext.getCmp("indsamlere_view_panel").hide();
	    Ext.getCmp("administration_view_panel").hide();
	    Ext.getCmp("grupper_view_panel").hide();
	    Ext.getCmp("kampagner_view_panel").show();
	} else {
	    Ext.getCmp("venues_view_panel").hide();
	    Ext.getCmp("indsamlere_view_panel").hide();
	    Ext.getCmp("grupper_view_panel").hide();
	    Ext.getCmp("administration_view_panel").hide();
	    Ext.getCmp("ruter_view_panel").hide();
	    Ext.getCmp("kampagner_view_panel").hide();
	}
    },
    

    onGridDblClicked: function(v, record, item, index, e, object) {
	if (v.getStore().id == "indsamlere_store") {
	    var data = Ext.getCmp('indsamlere_grid').getSelectionModel().getSelection()[0];
	    showIndsamlerForm('Rediger indsamler', true, data);
	} else if (v.getStore().id == "grupper_store") {
	    var data = Ext.getCmp('grupper_grid').getSelectionModel().getSelection()[0];
	    showGruppeForm('Rediger indsamlingsgruppe', true, data);
	} else if (v.getStore().id == "ruter_store") {
	    var data = Ext.getCmp('ruter_grid').getSelectionModel().getSelection()[0];
	    showRuteForm('Rediger ruter', true, data);
	} else if (v.getStore().id == "venues_store") {
	    if (!is_admin) return;
	    var data = Ext.getCmp('venues_grid').getSelectionModel().getSelection()[0];
	    showVenueForm('Rediger mødested', true, data);
	} else if (v.getStore().id == "kampagner_store") {
	    var data = Ext.getCmp('kampagner_grid').getSelectionModel().getSelection()[0];
	    showKampagneForm('Rediger kampagne', true, data);
	} else if (v.getStore().id == "gruppens_indsamlere_store") {
	    var data = Ext.getCmp('form_gruppe_indsamlerne').getSelectionModel().getSelection()[0];

	    check_warnings_and_commit_gruppe(gruppe_win.down('form').getForm(), gruppe_win, data, null);
	} else if (v.getStore().id == "gruppens_ruter_store") {
	    var data = Ext.getCmp('form_gruppe_ruterne').getSelectionModel().getSelection()[0];
	    
	    check_warnings_and_commit_gruppe(gruppe_win.down('form').getForm(), gruppe_win, null, data);
	}
    },
    
    onButtonClick: function(btn, e, eOpts) {
	if (btn.getId() == "logout_button") {
	    console.log(btn.getText());
	    window.open("./logout.php","_self")
	} else if (btn.getId() == "upload_csv_button") {
	    upload_csv()
	} else if (btn.getId() == "download_csv_button") {
	    download_csv()
	} else if (btn.getId() == "search_indsamlere_button") {
	    search("indsamlere");
	} else if (btn.getId() == "search_grupper_button") {
	    search("grupper");
	} else if (btn.getId() == "search_venues_button") {
	    search("venues");
	} else if (btn.getId() == "search_ruter_button") {
	    search("ruter");
	} else if (btn.getId() == "search_kampagner_button") {
	    search("kampagner");
	} else if (btn.getId() == "add_indsamler_button") {
	    showIndsamlerForm('Tilføj indsamler', false, null);
	} else if (btn.getId() == "add_gruppe_button") {
	    showGruppeForm('Tilføj gruppe', false, null);
	} else if (btn.getId() == "add_rute_button") {
	    showRuteForm('Tilføj rute', false, null);
	} else if (btn.getId() == "add_venue_button") {
	    showVenueForm('Tilføj mødested', false, null);
	} else if (btn.getId() == "add_kampagne_button") {
	    showKampagneForm('Tilføj kampagne', false, null);
	}	
	
    }
});

function upload_csv() {
    var form = Ext.getCmp('csv_filename_form');
    if(form.isValid()){
        form.submit({
            url: 'parse_csv.php',
            waitMsg: 'Uploader filen...',
            success: function (formPanel, action) {
		var data = Ext.decode(action.response.responseText);
		Ext.MessageBox.alert('Fil uploadet', data.msg);
            },
            failure: function (formPanel, action) {
		var data = Ext.decode(action.response.responseText);
		Ext.MessageBox.alert('Fejl', data.msg);
            }
        });
    }
}


function download_csv() {
    window.open('db_functions.php?function=export_csv_file', '_blank');
}


function search(type) {
    Ext.getCmp(type + "_grid").getSelectionModel().deselectAll(true);
    var store = Ext.getCmp(type + "_grid").getStore();  
    store.removeFilter(true);
    store.clearFilter(true);
    store.removeAll(true);
    if (type == "grupper" || type == "indsamlere") {
	store.filter([
	    {property: "search_value", value: Ext.getCmp("search_"+type+"_field").getRawValue()},
	    {property: "chosen_venue_value_uid", value: Ext.getCmp("choose_venue_"+type+"_combobox").getValue()}
	]);
    } else {
	store.filter([
	    {property: "search_value", value: Ext.getCmp("search_"+type+"_field").getRawValue()}
	]);
    }
}

function delete_row(type, func, uid_value) {
    
    Ext.Ajax.request({
	url: 'db_functions.php',
	method: 'post',
	params: {
	    function  : func,
	    uid: uid_value
	},
	success: function(response, object) {
	    var res = Ext.decode(response.responseText);
	 
            if (res.success == false){
		Ext.MessageBox.alert("Fejl", res.msg);
	    } else {
		search(type);
		
		//Ext.MessageBox.alert("Info", res.msg);
	    }
	}
    });
}


Ext.EventManager.onWindowResize(function () {
    adjust_size();
});

function adjust_size() {
    var width = Ext.getBody().getViewSize().width;
    var height = Ext.getBody().getViewSize().height;

    if (width < 1000) width = 1000;
    if (height < 500) height = 500;

    Ext.getCmp("viewport_view").setSize(width, height-15);
    Ext.getCmp("indsamlere_grid").setSize(width - 215, height - 300);
    Ext.getCmp("grupper_grid").setSize(width - 215, height - 300);
    Ext.getCmp("ruter_grid").setSize(width - 215, height - 260);
    Ext.getCmp("venues_grid").setSize(width - 215, height - 260);
    Ext.getCmp("kampagner_grid").setSize(width - 215, height - 260);
    Ext.getCmp("menulist_grid").setSize(180, height - 300);

}